/**
 * 首页事件处理器
 * 负责处理首页相关的所有事件和逻辑
 */
class HomeHandler {
  constructor(appState, apiService, uiUtils) {
    this.appState = appState;
    this.apiService = apiService;
    this.uiUtils = uiUtils;
    
    // 缓存连接测试结果
    this.lastTestedApiKey = null;
    this.lastTestResult = null;
    this.lastTestTime = null;
  }

  /**
   * 初始化首页
   */
  async init() {
    console.log("[HomeHandler] 初始化首页");

    // 延迟执行检测，确保 DOM 完全加载
    setTimeout(async () => {
      await this.loadHomePageData();
    }, 100);
  }

  /**
   * 加载首页数据
   */
  async loadHomePageData() {
    try {
      // 更新 Claude Code 版本信息
      await this.updateClaudeVersion();
      
      // 检查并测试 API Key 连通性
      await this.checkApiKeyConnection();

      this.uiUtils.addDetectionLog("检测完成", "success");
    } catch (error) {
      console.error("[HomeHandler] 加载首页数据失败:", error);
      this.uiUtils.addDetectionLog(
        `检测过程中发生错误: ${error.message}`,
        "error"
      );
    }
  }

  /**
   * 更新 Claude Code 版本信息
   */
  async updateClaudeVersion() {
    const versionElement = document.getElementById("header-claude-version");
    
    if (!versionElement) {
      console.warn("[HomeHandler] 找不到版本显示元素");
      return;
    }

    try {
      console.log("[HomeHandler] 开始更新 Claude Code 版本...");
      
      // 设置加载状态
      versionElement.textContent = "检测中...";
      versionElement.style.color = "#f59e0b"; // 橙色表示检测中

      // 获取版本信息
      const result = await this.apiService.getClaudeCodeVersion();
      console.log("[HomeHandler] 版本检测结果:", result);

      if (result.success && result.version) {
        let version = "未知版本";

        // 解析版本信息
        if (result.version.success && result.version.version) {
          if (typeof result.version.version === "string") {
            version = result.version.version;
          } else if (
            result.version.version.success &&
            result.version.version.version
          ) {
            version = result.version.version.version;
          }
        } else if (typeof result.version === "string") {
          version = result.version;
        }

        console.log("[HomeHandler] 解析后的版本:", version);
        versionElement.textContent = version;
        versionElement.style.color = "#22c55e"; // 绿色表示成功
      } else {
        console.warn("[HomeHandler] 版本检测失败");
        versionElement.textContent = "未检测到";
        versionElement.style.color = "#ef4444"; // 红色表示失败
      }
    } catch (error) {
      console.error("[HomeHandler] 更新版本信息失败:", error);
      versionElement.textContent = "检测失败";
      versionElement.style.color = "#ef4444";
    }
  }

  /**
   * 检查 API Key 连通性
   */
  async checkApiKeyConnection() {
    try {
      this.uiUtils.addDetectionLog("检查 API Key 配置和连通性...", "info");

      // 加载保存的模型配置
      const configResult = await window.electronAPI.invoke(
        "storage:load-model-config"
      );

      const headerApiStatus = document.getElementById("header-api-status");
      const apiStatusDot = document.getElementById("api-status-dot");

      if (
        !configResult.success ||
        !configResult.config ||
        !configResult.config.apiKey
      ) {
        // 未配置 API Key
        if (headerApiStatus) {
          headerApiStatus.textContent = "未配置";
        }
        if (apiStatusDot) {
          apiStatusDot.className = "status-dot disconnected";
        }
        this.uiUtils.addDetectionLog("API Key 未配置", "warning");
        
        // 清除缓存
        this.lastTestedApiKey = null;
        this.lastTestResult = null;
        this.lastTestTime = null;
        return;
      }

      const { provider, model, apiKey } = configResult.config;

      // 检查是否已经测试过相同的 API Key
      if (this.lastTestedApiKey === apiKey && this.lastTestResult) {
        console.log('[HomeHandler] 使用缓存的连接测试结果');
        this.uiUtils.addDetectionLog(`已配置 ${provider} - ${model}`, "info");
        this.uiUtils.addDetectionLog("使用缓存的连接测试结果", "info");
        
        // 使用缓存的测试结果
        if (this.lastTestResult.success) {
          if (headerApiStatus) {
            headerApiStatus.textContent = `${provider} - ${model}`;
          }
          if (apiStatusDot) {
            apiStatusDot.className = "status-dot connected";
          }
          this.uiUtils.addDetectionLog("✅ API 连接测试成功（缓存）", "success");
        } else {
          if (headerApiStatus) {
            headerApiStatus.textContent = "连接失败";
          }
          if (apiStatusDot) {
            apiStatusDot.className = "status-dot disconnected";
          }
          this.uiUtils.addDetectionLog(
            `❌ API 连接测试失败（缓存）: ${this.lastTestResult.message}`,
            "error"
          );
        }
        return;
      }

      // API Key 变更或首次测试，执行新的测试
      console.log('[HomeHandler] API Key 已变更或首次测试，执行连接测试');
      
      // 显示配置信息
      if (headerApiStatus) {
        headerApiStatus.textContent = "测试中...";
      }
      if (apiStatusDot) {
        apiStatusDot.className = "status-dot testing";
      }

      this.uiUtils.addDetectionLog(`已配置 ${provider} - ${model}`, "info");
      this.uiUtils.addDetectionLog("正在测试 API 连通性（最多等待 15 秒）...", "info");

      // 测试连接（使用公共方法）
      const testResult = await this.apiService.testApiConnection(apiKey, provider, model);
      console.log("🚀 ~ HomeHandler ~ checkApiKeyConnection ~ testResult:", testResult)

      // 缓存测试结果
      this.lastTestedApiKey = apiKey;
      this.lastTestResult = testResult;
      this.lastTestTime = Date.now();

      if (testResult.success) {
        // 连接成功 - 显示绿点
        if (headerApiStatus) {
          headerApiStatus.textContent = `${provider} - ${model}`;
        }
        if (apiStatusDot) {
          apiStatusDot.className = "status-dot connected";
        }
        this.uiUtils.addDetectionLog("✅ API 连接测试成功", "success");
      } else {
        // 连接失败 - 显示红点
        if (headerApiStatus) {
          headerApiStatus.textContent = "连接失败";
        }
        if (apiStatusDot) {
          apiStatusDot.className = "status-dot disconnected";
        }
        this.uiUtils.addDetectionLog(
          `❌ API 连接测试失败: ${testResult.message}`,
          "error"
        );
      }
    } catch (error) {
      console.error("[HomeHandler] 检查 API Key 连通性失败:", error);

      const headerApiStatus = document.getElementById("header-api-status");
      const apiStatusDot = document.getElementById("api-status-dot");

      if (headerApiStatus) {
        headerApiStatus.textContent = "检测异常";
      }
      if (apiStatusDot) {
        apiStatusDot.className = "status-dot disconnected";
      }

      this.uiUtils.addDetectionLog(`检测异常: ${error.message}`, "error");
    }
  }

  /**
   * 清除连接测试缓存（当 API Key 变更时调用）
   */
  clearConnectionTestCache() {
    console.log('[HomeHandler] 清除连接测试缓存');
    this.lastTestedApiKey = null;
    this.lastTestResult = null;
    this.lastTestTime = null;
  }


  /**
   * 处理安装 Claude Code 按钮点击
   */
  async handleInstallClaudeCode() {
    try {
      this.uiUtils.showLoading("正在安装 Claude Code...");

      const result = await this.apiService.installClaudeCode();

      this.uiUtils.hideLoading();

      if (result.success) {
        this.uiUtils.showMessage(result.message, "success");
        await this.appState.checkStatus(); // 重新检查状态
      } else {
        this.uiUtils.showMessage(result.message, "error");
      }
    } catch (error) {
      this.uiUtils.hideLoading();
      this.uiUtils.showMessage(`安装失败: ${error.message}`, "error");
    }
  }

  /**
   * 处理保存 API Key 按钮点击
   */
  async handleSaveApiKey() {
    const apiKeyInput = document.getElementById("api-key-input");
    if (!apiKeyInput) return;

    const apiKey = apiKeyInput.value.trim();
    if (!apiKey) {
      this.uiUtils.showMessage("请输入 API Key", "error");
      return;
    }

    try {
      this.uiUtils.showLoading("正在验证 API Key...");

      // 首先验证 API Key
      const validationResult = await this.apiService.validateApiKey(apiKey);

      if (!validationResult.success || !validationResult.valid) {
        this.uiUtils.hideLoading();
        this.uiUtils.showMessage(
          validationResult.message || "API Key 验证失败",
          "error"
        );
        return;
      }

      // 验证通过，保存 API Key
      const saveResult = await this.apiService.saveApiKey(apiKey);

      this.uiUtils.hideLoading();

      if (saveResult.success) {
        this.appState.apiKey = apiKey;
        this.uiUtils.showMessage("API Key 保存成功", "success");
        await this.appState.checkStatus(); // 更新状态显示
      } else {
        this.uiUtils.showMessage(`保存失败: ${saveResult.message}`, "error");
      }
    } catch (error) {
      this.uiUtils.hideLoading();
      this.uiUtils.showMessage(`保存失败: ${error.message}`, "error");
    }
  }

  /**
   * 处理清空日志按钮点击
   */
  handleClearLog() {
    this.uiUtils.clearDetectionLog();
  }

  /**
   * 绑定首页事件
   */
  bindEvents() {
    // 安装 Claude Code 按钮
    this.bindButton("install-btn", this.handleInstallClaudeCode.bind(this));

    // 保存 API Key 按钮
    this.bindButton("save-api-key-btn", this.handleSaveApiKey.bind(this));

    // 清空日志按钮
    this.bindButton("clear-log-btn", this.handleClearLog.bind(this));
  }

  /**
   * 绑定按钮事件
   * @param {string} buttonId - 按钮 ID
   * @param {Function} handler - 事件处理器
   */
  bindButton(buttonId, handler) {
    const button = document.getElementById(buttonId);
    if (button) {
      button.addEventListener("click", handler);
    }
  }

  /**
   * 清理事件监听器
   */
  cleanup() {
    // 移除所有事件监听器
    const buttons = ["install-btn", "save-api-key-btn", "clear-log-btn"];
    buttons.forEach((buttonId) => {
      const button = document.getElementById(buttonId);
      if (button) {
        button.replaceWith(button.cloneNode(true));
      }
    });
  }
}

// 导出到全局
window.HomeHandler = HomeHandler;
